
import {reqweb3 as runWitness} from './contract/reqweb3'
import axios from 'axios'

//获取鉴证商
   //实参
   //合约参数
   
   
   let contractParam = {
        req:'http://172.30.5.22:8655' , //鉴证请求地址
        addr:'0x90f3306e3032bcc905bf210902b66f99b584aa3f',   //订单合约地址
        abi:'[{"constant":false,"inputs":[{"name":"account","type":"address"},{"name":"services","type":"string"}],"name":"setServices","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"}],"name":"remove","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"},{"name":"name","type":"string"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"storageAddrList","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"},{"name":"website","type":"string"}],"name":"setWebsite","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"},{"name":"email","type":"string"}],"name":"setEmail","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"account","type":"address"}],"name":"getDetail","outputs":[{"name":"detail","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"page","type":"uint256"},{"name":"page_size","type":"uint256"}],"name":"getWitnessList","outputs":[{"name":"list","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"account","type":"address"}],"name":"getServices","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"},{"name":"name","type":"string"},{"name":"website","type":"string"},{"name":"email","type":"string"},{"name":"services","type":"string"}],"name":"add","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"witnessStorage","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousOwner","type":"address"},{"indexed":false,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]',

   }
   //用户地址
   let accountInfo = {
        address:'0xcEA5b326F281b32DE16591722941cceBF1c0ae6A',//用户地址
        privateKey:'d15b3eecd1d82582bcfb104e7c9a3fd7d895f4e09f622a308c0716b15deb712f'//私钥
   }
   function getWitnessList(contractParam,accountInfo){
    return new Promise((resolve, reject) => {
           var that = this;
		let idparam = 'getWitnessList 1 10';
        // let conParam = {    //合约参数
        //     addr:this.witnessAddr,
        //     abi:this.witnessAbi,
        //     req:this.witnessRequrl
        // }
        // console.log(contractParam)
		let reparam = runWitness(idparam,accountInfo,contractParam);     //检查参数
		// console.log('检查完参数',reparam)
		let sparam = ''
		if(reparam!=''){
		  if(reparam.params==''){
			  return
		  }
		  sparam  = reparam.params;   //axios需要的参数
		}
    // console.log(sparam)
		var decoder = reparam.decoder;
		axios.post(contractParam.req, {            //查询只读方法，查询该账号地址下的发送任务列表id
		  'jsonrpc': '2.0',
		  'method': 'call',
		  'params': sparam,       //返回参数
		  'id': 1
		}).then(res => {
			// console.log(res);
            let status = res.data.result.status;
          let ret = {
              status: status
          };
          let output = res.data.result.output;
          if (output !== '0x') {
              ret.output = decoder.decodeOutput(output);      //转码结果
          }
          return JSON.stringify(ret, null, "    ")
		}).then(res1=>{
            // console.log(JSON.parse(res1))
            // console.log('二',JSON.parse(res1).output.result[0]);
            var list = JSON.parse(JSON.parse(res1).output.result[0])
            let witnessNum = list[0];
            // console.log('任务总数',that.witnessNum)
            let addresslist = list.slice(1);
            resolve(addresslist)
            // console.log('鉴证商列表',addresslist)
            // if(witnessNum!= 0){       //总是为0
            //     var paramList = [];       //promise数组，需要使用promise.all执行
            //     addresslist.forEach(element => {   //组装下一步请求参数
            //         let conParam = {    //合约参数
            //             addr:this.witnessAddr,
            //             abi:this.witnessAbi,
            //             req:this.witnessRequrl
            //         }
            //         paramList.push(runWitness('getDetail '+ element,accountInfo, contractParam))
            //     });
            // // console.log('查看获取详情数组',promiseList);
            // }else{
            //     console.log('任务列表为空');
            //     this.getTasklistIng = ''
            //     return false
            // }
            //    return paramList
            }).catch(err=>{
                console.log(err)
            })
    })
        
            // .then(data=>{
            //     if(!data){       //列表为空
            //         return
            //     }
            //     console.log('查看任务列表id',data);
            //     var decoder = data[0].decoder;
            //     let sendParam = []
            //     data.forEach(item=>{
            //     sendParam.push(item.sendParam[0])     //每个任务id装载一个请求
            //     })
            //     var promiseList = [];
            //     data.forEach(element => {
            //     let request = axios.post(that.witnessRequrl, {
            //         "jsonrpc": "2.0",
            //         "method": "call",
            //         "params": element.params,       //返回参数
            //         "id": 1
            //     })
            //     // console.log('查看传入的参数',element.params)
            //     promiseList.push(request)
            //     });

            //     Promise.all(promiseList).then((values) => {
            //     // console.log('执行完了，查看内容1', values);
            //     var resultList = [];
            //     values.forEach(item=>{          //
            //         let status = item.data.result.status;
            //         let ret = {
            //         status: status
            //         };
            //         let output = item.data.result.output;
            //         if (output !== '0x') {
            //         // console.log(output)
            //         // console.log('output')
            //         ret.output = decoder.decodeOutput(output);
            //         }
            //         // console.log('第一次解码输出后',ret);
            //         // return
            //         let arr = ret.output.result
            //         // let reg = new RegExp('"',"g");
            //         let sssf = arr[0]
            //         // console.log('eee',sssf);
            //         let arrjson =JSON.parse(sssf.replace(/"{/g,'{').replace(/}"/g,'}'));
            //         // console.log('一条数据',arrjson)
            //         // var obj = arrjson;
            //         resultList.push(arrjson);
            //         // console.log('我是最终详情数据',resultList)
            //     })
            //     // console.log('我是最终详情数据',resultList)
            //     that.witnessStroreList = resultList;//


            //     that.originData.witness = JSON.parse(JSON.stringify(resultList));
            //     that.getWitnessService(resultList)
            //     // for(let ii =0;ii<resultList.length;ii++){
            //     //     resultList[ii].taskid = sendParam[ii]
            //     // }
            //     // console.log('查看最终任务列表详情数组',resultList);
            //     // this.tableData = resultList
            //     // this.getTasklistIng = ''
            //     });
            // })
    }
    //获取见证商详情
    let witnessAddr = '0xa76a9adf1ede2d13a7af22dd520e5c7f952b7fd8'//见证商地址
    function getWitnessDetail(witnessAddr,accountInfo,contractParam){
        return new Promise((resolve, reject) => {
             let reparam = runWitness('getDetail '+ witnessAddr,accountInfo, contractParam);
                let sparam = ''
                if(reparam!=''){
                if(reparam.params==''){
                    return
                }
                sparam  = reparam.params;   //axios需要的参数
                }
            // console.log(sparam)
                var decoder = reparam.decoder;
                axios.post(contractParam.req, {            //查询只读方法，查询该账号地址下的发送任务列表id
                'jsonrpc': '2.0',
                'method': 'call',
                'params': sparam,       //返回参数
                'id': 1
                }).then(res => {
                    // console.log(res);
                    let status = res.data.result.status;
                let ret = {
                    status: status
                };
                let output = res.data.result.output;
                if (output !== '0x') {
                    ret.output = decoder.decodeOutput(output);      //转码结果
                }
                return JSON.stringify(ret, null, "    ")
                }).then(res1=>{
                    let list = JSON.parse(JSON.parse(res1).output.result[0]);
                    let arrjson =JSON.parse(sssf.replace(/"{/g,'{').replace(/}"/g,'}'));
                    console.log(arrjson)
                    resolve(arrjson)
                })
                })
        

    }
    function getAllwitnessDetail(){
        return new Promise((resolve, reject) => {
            var that = this;
		let idparam = 'getWitnessList 1 10';
        
        // console.log(conParam)
		let reparam = runWitness(idparam,accountInfo,contractParam);    //检查参数
		// console.log('检查完参数',reparam)
		let sparam = ''
		if(reparam!=''){
		  if(reparam.params==''){
			  return
		  }
		  sparam  = reparam.params;   //axios需要的参数
		}
    // console.log(sparam)
		var decoder = reparam.decoder;
		axios.post(contractParam.req, {            //查询只读方法，查询该账号地址下的发送任务列表id
		  'jsonrpc': '2.0',
		  'method': 'call',
		  'params': sparam,       //返回参数
		  'id': 1
		}).then(res => {
			// console.log(res);
            let status = res.data.result.status;
          let ret = {
              status: status
          };
          let output = res.data.result.output;
          if (output !== '0x') {
              ret.output = decoder.decodeOutput(output);      //转码结果
          }
          return JSON.stringify(ret, null, "    ")
		}).then(res1=>{
            // console.log(JSON.parse(res1))
            // console.log('二',JSON.parse(res1).output.result[0]);
            var list = JSON.parse(JSON.parse(res1).output.result[0])
            let witnessNum = list[0];
            // console.log('任务总数',that.witnessNum)
            let addresslist = list.slice(1);
            console.log('鉴证商列表',addresslist)
            if(witnessNum!= 0){       //总是为0
                var paramList = [];       //promise数组，需要使用promise.all执行
                addresslist.forEach(element => {   //组装下一步请求参数
                    
                    paramList.push(runWitness('getDetail '+ element,accountInfo, contractParam))
                });
            // console.log('查看获取详情数组',promiseList);
            }else{
                console.log('任务列表为空');
                
                return false
            }
               return paramList
            }).then(data=>{
                if(!data){       //列表为空
                    return
                }
                console.log('查看任务列表id',data);
                var decoder = data[0].decoder;
                let sendParam = []
                data.forEach(item=>{
                sendParam.push(item.sendParam[0])     //每个任务id装载一个请求
                })
                var promiseList = [];
                data.forEach(element => {
                let request = axios.post(contractParam.req, {
                    "jsonrpc": "2.0",
                    "method": "call",
                    "params": element.params,       //返回参数
                    "id": 1
                })
                // console.log('查看传入的参数',element.params)
                promiseList.push(request)
                });
                var resultList = [];
                Promise.all(promiseList).then((values) => {
                // console.log('执行完了，查看内容1', values);
                
                values.forEach(item=>{          //
                    let status = item.data.result.status;
                    let ret = {
                    status: status
                    };
                    let output = item.data.result.output;
                    if (output !== '0x') {
                    // console.log(output)
                    // console.log('output')
                    ret.output = decoder.decodeOutput(output);
                    }
                    // console.log('第一次解码输出后',ret);
                    // return
                    let arr = ret.output.result
                    // let reg = new RegExp('"',"g");
                    let sssf = arr[0]
                    // console.log('eee',sssf);
                    let arrjson =JSON.parse(sssf.replace(/"{/g,'{').replace(/}"/g,'}'));
                    // console.log('一条数据',arrjson)
                    // var obj = arrjson;
                    resultList.push(arrjson);
                    // resolve(resultList)
                    // console.log('我是最终详情数据',resultList)
                })
                resolve(resultList)
                // console.log('我是最终详情数据',resultList)
                // that.witnessStroreList = resultList;//


                // that.originData.witness = JSON.parse(JSON.stringify(resultList));
                // that.getWitnessService(resultList)
                // for(let ii =0;ii<resultList.length;ii++){
                //     resultList[ii].taskid = sendParam[ii]
                // }
                // console.log('查看最终任务列表详情数组',resultList);
                // this.tableData = resultList
                // this.getTasklistIng = ''
                });
                // return resultList
            })
            
        })
    }
    const witness = {
        getWitnessList:getWitnessList,
        getWitnessDetail:getWitnessDetail,
        getAllwitnessDetail:getAllwitnessDetail


    }
    export default witness
    